package com.tes;

import java.util.List;

import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.TextMenuItem;
import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import com.tes.dao.HighScoreDAO;
import com.tes.model.HighScore;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.KeyEvent;

public class Menu extends BaseGameActivity implements IOnMenuItemClickListener {
	// screen size
	static final int CAMERA_WIDTH = 480;
	static final int CAMERA_HEIGHT = 320;

	// menu id
	static final int MENU_START = 100;
	// menu start dikasih pada index ke-100 (paling atas)
	static final int MENU_EXIT = 1;
	static final int MENU_BACK = MENU_START + 1;
	static final int MENU_RESET = MENU_BACK + 1;
	// menu exit dikasih pada index ke-0 (paling bawah)
	static final int MENU_ABOUT = MENU_EXIT + 1;
	// menu about dikasih pada index ke-1 (atasnya exit)
	static final int MENU_HIGHSCORE = MENU_START - 1;
	static final int MENU_TOGGLESOUND = MENU_HIGHSCORE - 1;
	static final int MENU_HELP = MENU_TOGGLESOUND - 1;
	// menu highscore dikasih pada index ke-99 (bawahnya start)

	// camera
	private Camera mCamera;

	// menu
	private BitmapTextureAtlas tFontMenu;
	private Font mFontMenu;

	// about
	private BitmapTextureAtlas tFontAbout;
	private Font mFontAbout;

	// score
	private BitmapTextureAtlas tFontScore;
	private Font mFontScore;

	// player
	private BitmapTextureAtlas tPlayer;
	private TiledTextureRegion mPlayer;

	// DURATION OF PLAYER
	private long[] playerDuration = { 100, 100, 100 };

	// set suara/music
	@Override
	public Engine onLoadEngine() {
		this.mCamera = GameResource.camera;

		Engine engine = new Engine(new EngineOptions(true,
				ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)
				.setNeedsMusic(true).setNeedsSound(true));

		return engine;
	}

	@Override
	public void onLoadResources() {
		// path
		FontFactory.setAssetBasePath("font/");
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		SoundFactory.setAssetBasePath("sound/");

		// ambil dari kelas GameResource yang sudah ada
		tFontMenu = GameResource.tFontChiller;
		mFontMenu = GameResource.mFontChiller;

		tFontAbout = GameResource.tFontAllHookedUp;
		mFontAbout = GameResource.mFontAllHookedUp;

		tFontScore = GameResource.tFontAiracobra;
		mFontScore = GameResource.mFontAiracobra;

		// player
		tPlayer = GameResource.tPlayer;
		mPlayer = GameResource.mPlayer;

		// load resource
		mEngine.getTextureManager().loadTextures(tFontMenu, tFontAbout,
				tFontScore, tPlayer);
		mEngine.getFontManager().loadFonts(mFontMenu, mFontAbout, mFontScore);
	}

	// Selalu return pada mainScenenya :)
	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());

		// MAIN SCENE
		Scene mainScene = new Scene();
		mainScene.setBackgroundEnabled(true);
		mainScene.setBackground(new ColorBackground(1.0f, 1.0f, 1.0f));

		// PLAYER
		final AnimatedSprite sPlayer = new AnimatedSprite(10,
				CAMERA_HEIGHT - 40, mPlayer);
		sPlayer.animate(playerDuration, 6, 8, true);

		// CREATE PHYSICSHANDLER FOR PLAYER
		final PhysicsHandler physicsPlayer = new PhysicsHandler(sPlayer);
		physicsPlayer.setVelocity(50, 0); // set kecepatan player
		sPlayer.registerUpdateHandler(physicsPlayer);

		// SET UPDATE HANDLER FOR EVERY PLAYER MOVEMENT
		sPlayer.registerUpdateHandler(new IUpdateHandler() {

			@Override
			public void reset() {
				// NONE
			}

			// Biar gambar jadi mondar-mandir
			@Override
			public void onUpdate(float pSecondsElapsed) {
				if (sPlayer.getX() >= CAMERA_WIDTH - 32) {
					physicsPlayer.setVelocityX(-physicsPlayer.getVelocityX());
					sPlayer.animate(playerDuration, 3, 5, true);
				}

				if (sPlayer.getX() <= 0) {
					physicsPlayer.setVelocityX(-physicsPlayer.getVelocityX());
					sPlayer.animate(playerDuration, 6, 8, true);
				}
			}
		});

		mainScene.attachChild(sPlayer);

		return mainScene;
	}

	@Override
	public void onLoadComplete() {
		// MENU SCENE
		MenuScene menuScene = this.createMenuScene();
		this.getEngine().getScene().setChildScene(menuScene);
	}

	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {

		MenuScene menuScene = null;

		switch (pMenuItem.getID()) {
		case MENU_START:
			Intent intent = new Intent(this, SelectLevel.class);
			this.startActivity(intent);
			break;

		case MENU_HIGHSCORE:
			menuScene = this.createHighScore();
			this.getEngine().getScene().clearChildScene();
			this.getEngine().getScene().setChildScene(menuScene);
			break;

		case MENU_HELP:
			menuScene = this.createHelp();
			this.getEngine().getScene().clearChildScene();
			this.getEngine().getScene().setChildScene(menuScene);
			break;

		case MENU_ABOUT:
			menuScene = this.createAbout();
			this.getEngine().getScene().clearChildScene();
			this.getEngine().getScene().setChildScene(menuScene);
			break;

		case MENU_RESET:
			List<HighScore> scores = new HighScoreDAO(getApplicationContext())
					.gets();
			for (HighScore highScore : scores) {
				highScore.setScore(0);
				new HighScoreDAO(getApplicationContext())
						.updateScore(highScore);
			}

			menuScene = this.createHighScore();
			this.getEngine().getScene().clearChildScene();
			this.getEngine().getScene().setChildScene(menuScene);
			break;

		case MENU_BACK:
			menuScene = this.createMenuScene();
			this.getEngine().getScene().clearChildScene();
			this.getEngine().getScene().setChildScene(menuScene);
			break;

		case MENU_EXIT:
			AlertDialog alertDialogExit = new AlertDialog.Builder(this)
					.create();
			alertDialogExit.setTitle("Exit Application");
			alertDialogExit.setMessage("Do you want to exit ?");

			alertDialogExit.setButton(AlertDialog.BUTTON_POSITIVE, "Yes",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							Menu.this.finish();
						}
					});

			alertDialogExit.setButton(AlertDialog.BUTTON_NEGATIVE, "No",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							arg0.cancel();
						}
					});
			alertDialogExit.show();
			break;

		default:
			break;
		}

		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setIcon(android.R.drawable.ic_dialog_alert);
			alert.setTitle("Exit Application");
			alert.setMessage("Do you want to exit ?");

			alert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Menu.this.getEngine().getCamera().reset();
							Menu.this.finish();
						}

					});
			alert.setNegativeButton("No", null);
			alert.show();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	protected MenuScene createMenuScene() {
		MenuScene menuScene = new MenuScene(this.mCamera);

		IMenuItem startMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_START, this.mFontMenu, "PLAY"), 1.0f, 1.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		menuScene.addMenuItem(startMenuItem);

		IMenuItem highScoreItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_HIGHSCORE, this.mFontMenu, "HIGH SCORES"), 1.0f, 1.0f,
				0.0f, 0.0f, 0.0f, 0.0f);
		menuScene.addMenuItem(highScoreItem);

		// IMenuItem toggleSoung = new ColorMenuItemDecorator(new TextMenuItem(
		// MENU_TOGGLESOUND, this.mFontMenu, "TOGGLE SOUND"), 1.0f, 0.0f,
		// 0.0f, 0.0f, 0.0f, 0.0f);
		// menuScene.addMenuItem(toggleSoung);

		IMenuItem help = new ColorMenuItemDecorator(new TextMenuItem(MENU_HELP,
				this.mFontMenu, "HELP"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
		menuScene.addMenuItem(help);

		IMenuItem aboutMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_ABOUT, this.mFontMenu, "ABOUT"), 1.0f, 1.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		menuScene.addMenuItem(aboutMenuItem);

		IMenuItem exitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_EXIT, this.mFontMenu, "EXIT"), 1.0f, 1.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		menuScene.addMenuItem(exitMenuItem);

		menuScene.buildAnimations();
		menuScene.setBackgroundEnabled(false);
		// menuScene.setBackgroundEnabled(true);
		// menuScene.setBackground(new ColorBackground(0.0f, 0.0f, 1.0f));
		menuScene.setOnMenuItemClickListener(this);

		return menuScene;
	}

	protected MenuScene createHighScore() {
		MenuScene menuScene = new MenuScene(this.mCamera);

		float x = 20;
		float y = 10;
		float temp = 0;

		// judul
		IMenuItem scoreMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				-1, this.mFontMenu, "HIGH-SCORE"), 1.0f, 0.0f, 0.0f, 1.0f,
				0.0f, 0.0f);
		scoreMenuItem.setPosition(
				(CAMERA_WIDTH - scoreMenuItem.getWidth()) / 2, y);
		y = y + 10 + scoreMenuItem.getHeight();
		temp = y;
		menuScene.addMenuItem(scoreMenuItem);

		List<HighScore> listScore = new HighScoreDAO(getApplicationContext())
				.gets();
		for (HighScore highScore : listScore) {

			if (highScore.getLevel() == 6) {
				x += (CAMERA_WIDTH / 2);
				y = temp;
			}

			IMenuItem menuItem = new ColorMenuItemDecorator(new TextMenuItem(
					-1, this.mFontScore, highScore.getLevel() + "          "
							+ highScore.getScore()), 1.0f, 0.0f, 0.0f, 1.0f,
					0.0f, 0.0f);
			menuItem.setPosition(x, y);
			y = y + 10 + menuItem.getHeight();
			menuScene.addMenuItem(menuItem);
		}

		// menu reset
		IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_RESET, this.mFontMenu, "RESET"), 1.0f, 0.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		resetMenuItem.setPosition(
				(CAMERA_WIDTH / 4) - (resetMenuItem.getWidth() / 2),
				CAMERA_HEIGHT - 50);
		menuScene.addMenuItem(resetMenuItem);

		// menu back
		IMenuItem backMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_BACK, this.mFontMenu, "BACK"), 1.0f, 0.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		backMenuItem.setPosition(
				(CAMERA_WIDTH * 0.75f) - (backMenuItem.getWidth() / 2),
				CAMERA_HEIGHT - 50);
		menuScene.addMenuItem(backMenuItem);

		menuScene.setBackgroundEnabled(false);
		menuScene.setOnMenuItemClickListener(this);

		return menuScene;
	}

	protected MenuScene createHelp() {
		MenuScene menuScene = new MenuScene(this.mCamera);

		IMenuItem aboutMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				-1, this.mFontMenu, "HELP"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f);
		aboutMenuItem.setPosition(
				(CAMERA_WIDTH - aboutMenuItem.getWidth()) / 2, 20);
		menuScene.addMenuItem(aboutMenuItem);

		String text = "Tono sangat suka berpetulang, \n"
				+ "namun dia memiliki masalah dengan perutnya. \n"
				+ "Sekarang dia ingin berpetualang, \n"
				+ "bantu dia untuk menikmati liburannya. \n\n"
				+ "HINT : \n"
				+ "- Kertas Toilet akan menambah nilai \n"
				+ "- Menabrak orang akan membuat mu lambat \n"
				+ "- Tono sangat takut dengan Hantu \n"
				+ "- Bost mempercepat kamu dan deadline mu";
		Text isiText = new Text(0, 0, mFontAbout, text);
		isiText.setPosition((CAMERA_WIDTH - isiText.getWidth()) / 2,
				aboutMenuItem.getY() + aboutMenuItem.getHeight() + 20);
		menuScene.attachChild(isiText);

		IMenuItem backMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_BACK, this.mFontMenu, "BACK"), 1.0f, 0.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		backMenuItem.setPosition((CAMERA_WIDTH - backMenuItem.getWidth()) / 2,
				CAMERA_HEIGHT - backMenuItem.getHeight() - 20);
		menuScene.addMenuItem(backMenuItem);

		menuScene.setBackgroundEnabled(false);
		menuScene.setOnMenuItemClickListener(this);

		return menuScene;
	}

	protected MenuScene createAbout() {
		MenuScene menuScene = new MenuScene(this.mCamera);

		IMenuItem aboutMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				-1, this.mFontMenu, "ABOUT"), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
				0.0f);
		aboutMenuItem.setPosition(
				(CAMERA_WIDTH - aboutMenuItem.getWidth()) / 2, 20);
		menuScene.addMenuItem(aboutMenuItem);

		String text = "Pembuat \n" + "Jadi Budi Laksono \n"
				+ "Rahmat Yudi Wibowo \n\n" + "Credit \n"
				+ "http://untamed.wild-refuge.net/rpgxp.php \n"
				+ "http://wiki.andengine.org/AndEngine \n"
				+ "http://downloads.rpg-palace.com/ \n"
				+ "Jiwandono Suryo, Ong Yossi, dkk";
		Text isiText = new Text(0, 0, mFontAbout, text);
		isiText.setPosition((CAMERA_WIDTH - isiText.getWidth()) / 2,
				aboutMenuItem.getY() + aboutMenuItem.getHeight() + 20);
		menuScene.attachChild(isiText);

		IMenuItem backMenuItem = new ColorMenuItemDecorator(new TextMenuItem(
				MENU_BACK, this.mFontMenu, "BACK"), 1.0f, 0.0f, 0.0f, 0.0f,
				0.0f, 0.0f);
		backMenuItem.setPosition((CAMERA_WIDTH - backMenuItem.getWidth()) / 2,
				CAMERA_HEIGHT - backMenuItem.getHeight() - 20);
		menuScene.addMenuItem(backMenuItem);

		menuScene.setBackgroundEnabled(false);
		menuScene.setOnMenuItemClickListener(this);

		return menuScene;
	}
}
